﻿CREATE PROCEDURE [dbo].[AbsenceLinesUpdate]
(--Отказ покупателю в случае отсутствия товара в продаже
	@GoodsId int,
	@Qntty int,		
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,    
	@Original_MD datetime 
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @orgDocId int

SET NOCOUNT ON
IF (@GoodsId Is Null) OR (@Qntty Is Null)
OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocId = DocId FROM CD.ManageDocLines
WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <= 0)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Количество д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;

UPDATE CD.ManageDocLines SET 
[GoodsId] = @GoodsId,
Qntty = @Qntty,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id;

SELECT Id, [DocId], [GoodsId], Qntty, 
[Note], [MD], [MW]
FROM CD.ManageDocLines WHERE Id = @Original_Id 
RETURN 0